
import pandas as pd
import numpy as np


def load_data(file_path):
    data = pd.read_csv(file_path, header=None)
    return data


def euclidean_distance(point1, point2):
    return np.sqrt(np.sum((point1 - point2) ** 2))


class KNN:
    def __init__(self, k=3):
        self.k = k
        self.x_train = None
        self.y_train = None

    def fit(self, x, y):
        self.x_train = x
        self.y_train = y

    def predict(self, x_test):
        predictions = []
        for test_point in x_test:
            distances = []
            for index, train_point in enumerate(self.x_train):
                distance = euclidean_distance(test_point, train_point)
                distances.append((distance, self.y_train[index]))
            distances.sort(key=lambda x: x[0])  
            neighbors = distances[:self.k]  
            
           
            class_votes = {}
            for _, vote in neighbors:
                if vote in class_votes:
                    class_votes[vote] += 1
                else:
                    class_votes[vote] = 1
            
            predicted_class = max(class_votes.items(), key=lambda x: x[1])[0]
            predictions.append(predicted_class)
        return predictions


if __name__ == '__main__':
    
    wine_data = load_data('wine.csv')
    
    
    X = wine_data.iloc[:, 1:].values 
    y = wine_data.iloc[:, 0].values   

 
    kkn = KNN(k=3)
    kkn.fit(X, y)

    
    sample = X[0] 
    prediction = kkn.predict([sample])
    print("KNN预测结果：", prediction)